package com.chang.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chang.reggie.common.R;
import com.chang.reggie.dto.DishDto;
import com.chang.reggie.entity.Category;
import com.chang.reggie.entity.Dish;
import com.chang.reggie.entity.DishFlavor;
import com.chang.reggie.service.CategoryService;
import com.chang.reggie.service.DishFlavorService;
import com.chang.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Chang
 * @date 2022-09-14 22:41
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        // 创建分页构造器
        Page<Dish> dishPage = new Page<>(page, pageSize);
        // 创建条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 添加查询条件
        queryWrapper.like(StrUtil.isNotBlank(name), Dish::getName, name);
        // 添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        // 执行查询
        dishService.page(dishPage, queryWrapper);

        // dishPage 中缺少 categoryName，创建 DishDto 的分页对象
        Page<DishDto> dishDtoPage = new Page<>();
        // 对象拷贝
        BeanUtil.copyProperties(dishPage, dishDtoPage, "records");

//        List<DishDto> dishDtoRecords = new ArrayList<>();
//        List<Dish> dishRecords = dishPage.getRecords();
//        for (Dish dish : dishRecords) {
//            DishDto dishDto = new DishDto();
//            BeanUtil.copyProperties(dish, dishDto);
//            Category category = categoryService.getById(dish.getCategoryId());
//            dishDto.setCategoryName(category.getName());
//            dishDtoRecords.add(dishDto);
//        }
//        dishDtoPage.setRecords(dishDtoRecords);

        List<Dish> dishRecords = dishPage.getRecords();
        List<DishDto> dishDtoRecords = dishRecords.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtil.copyProperties(dish, dishDto);
            Category category = categoryService.getById(dish.getCategoryId());
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtoRecords);
        return R.success(dishDtoPage);
    }

    /**
     * 根据 id 获取菜品
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getDishById(@PathVariable Long id) {
        log.info("id：{}", id);
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("菜品：{}", dishDto);
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(String[] ids) {
        for (String id : ids) {
            dishService.removeById(id);
        }
        return R.success("删除菜品成功");
    }

    /**
     * 启售/停售菜品
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> sale(@PathVariable int status, String[] ids) {
        for (String id : ids) {
            Dish dish = dishService.getById(id);
            if (Objects.equals(status, dish.getStatus())) {
                continue;
            }
            dish.setStatus(status);
            dishService.updateById(dish);
        }

        return R.success("修改成功");
    }

    /**
     * 根据条件查询对应菜品数据
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        // 创建条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 添加查询条件，查询状态为1（启售状态）
        queryWrapper.eq(Dish::getCategoryId, dish.getCategoryId()).eq(Dish::getStatus, 1);
        // 添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        // 执行查询
        List<Dish> dishList = dishService.list(queryWrapper);


        List<DishDto> dishDtoList = dishList.stream().map(new Function<Dish, DishDto>() {
            @Override
            public DishDto apply(Dish dish) {
                DishDto dishDto = new DishDto();
                BeanUtil.copyProperties(dish, dishDto);
                Category category = categoryService.getById(dish.getCategoryId());
                dishDto.setCategoryName(category.getName());
                LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(DishFlavor::getDishId, dish.getId());
                List<DishFlavor> dishFlavors = dishFlavorService.list(wrapper);
                dishDto.setFlavors(dishFlavors);
                return dishDto;
            }
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }

}
